//
//  UIView+BOCNetworkImage.m
//  BOCImageTools
//
//  Created by LeungChaos on 16/5/11.
//  Copyright © 2016年 liang. All rights reserved.
//

#import "UIView+BOCNetworkImage.h"
#import "BOCImageDownloadTask.h"
#import <objc/runtime.h>

@implementation UIView (BOCNetworkImage)

static char _downloadTaskDictIdentifier;

//+ (void)load
//{
//    Method m1 = class_getInstanceMethod(self, NSSelectorFromString(@"dealloc"));
//    Method m2 = class_getInstanceMethod(self, NSSelectorFromString(@"boc_dealloc"));
//    
//    method_exchangeImplementations( m1, m2);
//}

#pragma mark - DownlaodTask
// setter func
- (NSMutableDictionary<NSString *,BOCImageDownloadTask *> *)allDownloadTask
{
    NSMutableDictionary *dict = objc_getAssociatedObject(self, &_downloadTaskDictIdentifier);
    if (dict == nil) {
        dict = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, &_downloadTaskDictIdentifier, dict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return dict;
}
// getter func
- (void)setDownloadTask:(BOCImageDownloadTask *)task forKey:(NSString *)key
{
    BOCImageDownloadTask *obj = [self.allDownloadTask objectForKey:key];
    if (obj == nil && task != nil) {
        NSMutableDictionary *dic = self.allDownloadTask;
        [dic setObject:task forKey:key];
    }
}
//
- (void)removeDownloadTaskForKey:(NSString *)key
{
    BOCImageDownloadTask *obj = [self.allDownloadTask objectForKey:key];
    if (obj) {
        [obj setCancel:YES];
//        BOCLog(@"BOCImageDownloadTsask Cancelled");
        [self.allDownloadTask removeObjectForKey:key];
    }
}

- (void)cancelAllDownlaodTask
{
    NSMutableDictionary *dict = self.allDownloadTask;
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString * _Nonnull key, BOCImageDownloadTask * _Nonnull obj, BOOL * _Nonnull stop) {
        [obj setCancel:YES];
//        BOCLog(@"BOCImageDownloadTask Cancelled");
    }];
    [dict removeAllObjects];
}

//
//- (void)boc_dealloc
//{


//    [[NSNotificationCenter defaultCenter]removeObserver:self name:BOCDownloadCompletedNotification object:nil];
//    [self boc_dealloc];
//}

@end
